<template>
  <div class="categories">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-button type="primary" @click="addCategoriesDialog = true"
        >添加分类</el-button
      >
      <el-table
        border
        :data="CategoriesList"
        row-key="cat_id"
        lazy
        :load="load"
        style="width: 100%; margin-bottom: 20px;"
        :tree-props="{ hasChildren: 'hasChildren', children: 'children' }"
      >
        <el-table-column label="#" type="index" width="46">
          <!-- <template #default="{row}">
            <div v-if="row.cat_level === 0">{{ 0 }}</div>
          </template> -->
          <template #default="{row}">
            <div v-if="row.cat_level === 0">{{ indexId(row.cat_id) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" prop="cat_name"> </el-table-column>
        <el-table-column label="是否有效" prop="cat_deleted">
          <template #default="{ row }">
            <i
              v-if="!row.cat_deleted"
              class="el-icon-success"
              style="color: #39ce39;"
            ></i>
            <i v-else class="el-icon-error" style="color: #f56c6c;"></i>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="cat_level">
          <template #default="{ row }">
            <el-tag
              size="mini"
              effect="dark"
              color="#409eff"
              v-if="row.cat_level === 0"
              type="primary"
              >一级</el-tag
            >
            <el-tag
              size="mini"
              effect="dark"
              color="#67c23a"
              v-else-if="row.cat_level === 1"
              type="success"
              >二级</el-tag
            >
            <el-tag
              size="mini"
              effect="dark"
              color="#e6a23c"
              v-else
              type="warning"
              >三级</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="putCategoriesV(row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="delCategories(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="CategoriesFrom.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="CategoriesFrom.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="CategoriesFrom.total"
      >
      </el-pagination>

      <el-dialog
        title="添加商品分类"
        :visible.sync="addCategoriesDialog"
        width="50%"
        @close="closeCate"
      >
        <el-form
          label-width="80px"
          :model="addCategoriesFrom"
          ref="addCategoriesFrom"
          :rules="rules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCategoriesFrom.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              :options="parentCategoriesList"
              :props="{
                checkStrictly: true,
                label: 'cat_name',
                value: 'cat_id',
              }"
              clearable
              v-model="addCategoriesFrom.cat_pid"
              ref="parentCate"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoriesDialog = false">取 消</el-button>
          <el-button type="primary" @click="addCategories">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="修改分类" :visible.sync="dialogVisible" width="50%">
        <el-form
          label-width="80px"
          ref="putForm"
          :model="putFrom"
          :rules="rules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="putFrom.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="putCategories">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  name: 'Categories',
  data() {
    return {
      dialogVisible: false,
      CategoriesList: [],
      parentCategoriesList: [],
      index: 0,
      addCategoriesDialog: false,
      putFrom: {
        cat_name: '',
        cat_id: '',
      },
      CategoriesFrom: {
        type: '',
        pagenum: 1,
        pagesize: 10,
        total: 0,
      },
      addCategoriesFrom: {
        cat_pid: [],
        cat_name: '',
      },
      rules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    digui(arr, id) {
      arr.some((v, i) => {
        // console.log(v);
        if (v.cat_id === id) {
          arr.splice(i, 1);
          return true;
        }
        if (v.children) {
          return this.digui(v.children, id);
        }
      });
    },
    // 删除分类
    delCategories(row) {
      const id = row.cat_id;
      // console.log(id);
      // console.log(this.CategoriesList);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return this.__apis.goods.deleteCategories(id);
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success('删除成功');
            this.digui(this.CategoriesList, id);
            // this.getCategoriesList();
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 修改分类
    putCategories() {
      this.__apis.goods
        .putCategories({
          cat_name: this.putFrom.cat_name,
          cat_id: this.putFrom.cat_id,
        })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success('修改成功');
            this.getCategoriesList();
            this.dialogVisible = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        });
    },
    // 获取用来修改的分类数据
    putCategoriesV(row) {
      this.putFrom.cat_id = row.cat_id;
      this.putFrom.cat_name = row.cat_name;
      this.dialogVisible = true;
    },
    // 每页数量改变
    handleSizeChange(size) {
      this.CategoriesFrom.pagesize = size;
      this.getCategoriesList();
    },
    // 页码改变
    handleCurrentChange(current) {
      this.CategoriesFrom.pagenum = current;
      this.getCategoriesList();
    },
    // 移除检验结果
    closeCate() {
      this.$refs.addCategoriesFrom.clearValidate();
      this.$refs.parentCate.checkedValue = '';
      this.addCategoriesFrom.cat_name = '';
    },
    // 添加商品分类
    addCategories() {
      this.$refs.addCategoriesFrom
        .validate()
        .then(() => {
          let id = this.addCategoriesFrom.cat_pid;
          id = id.length > 0 ? id[id.length - 1] : 0;
          return this.__apis.goods.addCategories({
            cat_pid: id,
            cat_name: this.addCategoriesFrom.cat_name,
            cat_level: this.addCategoriesFrom.cat_pid.length,
          });
        })
        .then((res) => {
          // console.log(res);
          if (res.data.meta.status === 201) {
            this.$message.success('添加成功');
            this.getCategoriesList();
            this.addCategoriesDialog = false;
          } else {
            this.$message.error(res.data.meta.msg);
          }
        })
        .catch(() => {});
    },
    // 懒加载
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve(tree.children);
      }, 500);
    },
    // 添加懒加载的子级识别
    addHasChildren: function (node) {
      if (!node.children || node.children.length === 0) {
        return;
      }
      node.hasChildren = true;
      node.children.forEach((v) => {
        this.addHasChildren(v);
      });
    },
    // 获取分类数据列表
    getCategoriesList() {
      this.__apis.goods
        .getCategoriesList({
          type: this.CategoriesFrom.type,
          pagenum: this.CategoriesFrom.pagenum,
          pagesize: this.CategoriesFrom.pagesize,
        })
        .then((res) => {
          // console.log(res);
          this.CategoriesFrom.total = res.data.data.total;
          this.CategoriesList = res.data.data.result;
          this.CategoriesList.forEach((v) => {
            this.addHasChildren(v);
          });

          // 更新父级分类
          this.getParentCategoriesList();
        });
    },
    // 获取父级分类
    getParentCategoriesList() {
      this.__apis.goods
        .getCategoriesList({
          type: '',
          pagenum: '',
          pagesize: '',
        })
        .then((res) => {
          // console.log(res);
          // 修改为父级分类列表
          this.parentCategoriesList = JSON.parse(JSON.stringify(res.data.data));
          this.parentCategoriesList.forEach((v) => {
            if (v.children) {
              v.children.forEach((v) => {
                if (v.children) {
                  v.children = null;
                }
              });
            }
          });
        });
    },
  },
  created() {
    this.getCategoriesList();
  },
  computed: {
    // 设置索引
    indexId() {
      return function (index) {
        let id = 0;
        this.CategoriesList.forEach((v, i) => {
          if (v.cat_id === index) {
            id = i;
          }
        });
        return id + 1;
      };
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
}
.el-card {
  margin-top: 15px;
  min-width: 1124px;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
